package com.bx.implatform.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.bx.implatform.enums.ResultCode;
import com.bx.implatform.exception.GlobalException;
import com.bx.implatform.service.TokenService;
import com.bx.implatform.session.UserSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@AllArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //从 http 请求头中取出 token
        String token = request.getHeader("accessToken");
        if (StrUtil.isEmpty(token)) {
            log.error("未登陆，url:{}", request.getRequestURI());
            throw new GlobalException(ResultCode.NO_LOGIN);
        }
        LoginUser loginUser = tokenService.getLoginUser(token);
        UserSession userSession = new UserSession();
        userSession.setUserId(loginUser.getUserId());
        userSession.setTerminal(loginUser.getTerminal());
        userSession.setUserName(loginUser.getUser().getUserName());
        userSession.setNickName(loginUser.getUser().getNickName());
        request.setAttribute("session", userSession);
        return true;
    }
}
